import subprocess
import logging
import datetime

# Configure logging
logging.basicConfig(filename='backup_mounted_partition.log', level=logging.INFO, 
                    format='%(asctime)s - %(levelname)s - %(message)s')

def log_message(message):
    """Log a message to both console and log file."""
    print(message)
    logging.info(message)

def run_command(command):
    """Run a shell command and handle errors."""
    try:
        result = subprocess.run(command, check=True, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        output = result.stdout.decode('utf-8')
        log_message(output)
    except subprocess.CalledProcessError as e:
        error_message = f"Error executing command: {e.cmd}\n{e.stderr.decode('utf-8')}"
        log_message(error_message)
        exit(1)

def get_current_deployment():
    """Get the current OSTree deployment checksum."""
    try:
        result = subprocess.run(['ostree', 'admin', 'status'], check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        output = result.stdout.decode('utf-8')
        log_message("Current OSTree admin status:\n" + output)
        lines = output.split('\n')
        for line in lines:
            if 'Deployment' in line:
                parts = line.split()
                checksum = parts[1]
                return checksum
    except subprocess.CalledProcessError as e:
        error_message = f"Error getting current deployment: {e.cmd}\n{e.stderr.decode('utf-8')}"
        log_message(error_message)
        exit(1)

def create_backup(repo_path, checksum):
    """Create a backup of the current system state using the deployment checksum."""
    timestamp = datetime.datetime.now().strftime("%Y%m%d%H%M%S")
    backup_ref = f"backup-{timestamp}"
    log_message(f"Creating backup with reference: {backup_ref} using checksum: {checksum}")
    run_command(f"ostree refs --repo={repo_path} --create={backup_ref} {checksum}")

def main():
    repo_path = "/ostree/repo"
    
    # Get the current deployment checksum
    checksum = get_current_deployment()
    
    # Create a backup of the current system state
    create_backup(repo_path, checksum)

if __name__ == "__main__":
    main()

